import Ability from '@ohos.application.Ability'
import wantAgent from '@ohos.wantAgent';
import backgroundTaskManager from '@ohos.backgroundTaskManager';

import {
    MSG_SEND_METHOD,
    START_BG_TASK,
    STOP_BG_TASK,
    EVENT_ID
} from '../model/const';
import MySequenceable from '../model/MySequenceable';
import ServiceModel from '../model/ServiceModel';
import Logger from '../model/Logger';

const TAG = "BG_TASK_serviceExtAbility";

let bgTaskContext = null;
let wantAgentInfo = {
    wants: [
        {
            bundleName: "com.example.myapplication",
            abilityName: "com.example.myapplication.MainAbility"
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
function callback(err, data) {
    if (err) {
        Logger.error(TAG, `Operation failed Cause: ${JSON.stringify(err)}`)
        return
    }

    Logger.info(TAG, `Operation startBackgroundRunning succeeded ====${globalThis.stageText2}`)

}

function start() {
    wantAgent.getWantAgent(wantAgentInfo).then((data) => {
        Logger.info(TAG, `startBackground begin`)
        backgroundTaskManager.startBackgroundRunning(bgTaskContext, backgroundTaskManager.BackgroundMode.DATA_TRANSFER, data, callback);
    })
}
function stop() {
    backgroundTaskManager.stopBackgroundRunning(bgTaskContext).then(() => {
        console.info("Operation stopBackgroundRunning succeeded");
    }).catch((err) => {
        console.error("Operation stopBackgroundRunning failed Cause: " + err);
    });
}

let serExtModel = new ServiceModel();
function sendMsgCallback(data) {
    Logger.log(TAG, 'CalleeSortFunc called')

    // 获取Caller发送的序列化数据
    let receivedData = new MySequenceable(0, '')
    data.readSequenceable(receivedData)
    Logger.log(TAG, `receiveData[${receivedData.num}, ${receivedData.str}]`);
    if (receivedData.str === START_BG_TASK) {
        start();
        let innerEvent = { eventId: EVENT_ID }
        serExtModel.connectServiceExtAbility(innerEvent, (code, msg)=> {
            Logger.log(TAG, `connectServiceExtAbility remote result ${code} ${msg}`);
        });
    } else if (receivedData.str === STOP_BG_TASK) {
        stop();
    }
    // 返回序列化数据result给Caller
    return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`)
}


export default class DataTransAbility extends Ability {
    onCreate(want, launchParam) {
        console.log("[Demo] MainAbility onCreate")
        globalThis.abilityWant = want;

        this.callee.on('test', sendMsgCallback);

        try {
            this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
        } catch (error) {
            Logger.error(TAG, `${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
        }
        bgTaskContext = this.context;
    }

    onDestroy() {
        console.log("[Demo] MainAbility onDestroy");

        try {
            this.callee.off(MSG_SEND_METHOD)
        } catch (error) {
            console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`)
        }
    }

    onWindowStageCreate(windowStage) {
        // Main window is created, set main page for this ability
        console.log("[Demo] MainAbility onWindowStageCreate")

        windowStage.loadContent("pages/index", (err, data) => {
            console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data))
        });
    }

    onWindowStageDestroy() {
        // Main window is destroyed, release UI related resources
        console.log("[Demo] MainAbility onWindowStageDestroy")
    }

    onForeground() {
        // Ability has brought to foreground
        console.log("[Demo] MainAbility onForeground")
    }

    onBackground() {
        // Ability has back to background
        console.log("[Demo] MainAbility onBackground")
    }
};